﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Dapper_Core.BLL.Impl;
using Dapper_Core.Common;
using Dapper_Core.DAL.Impl;
using Dapper_Core.Model;
using Dapper_Core.Table;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using OfficeOpenXml;

namespace Dapper_Core.Web.Areas.Agent.Controllers
{
    public class AgentSamaccountController : Controller
    {
        private readonly IHostingEnvironment _hostingEnvironment;

        public AgentSamaccountController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        public IActionResult GetPageList(int rowsPerPage, int offsetRows, AgentSamAccount agentSamAccount)
        {
            if (rowsPerPage < 1 || offsetRows < 0)
            {
                return Json(new { total = 0, rows = new List<AgentSamAccount>() });
            }
            try
            {
                if (agentSamAccount.CreateDateEnd != null)
                {
                    //申请截止日期是2019-02-02，查询数据应该包含02-02这一天，
                    //由于前台只返回年月日，我们将截止日期改为02-03，然后申请日期<=02-03就能包含02-02的数据了
                    agentSamAccount.CreateDateEnd = Convert.ToDateTime(agentSamAccount.CreateDateEnd).AddDays(1);
                }
                Expression<Func<AgentSamAccount, bool>> exp = GetExpression(agentSamAccount);
                AgentSamAccountBusiness agentSamaccountBusiness = new AgentSamAccountBusiness();
                List<AgentSamAccount> list = agentSamaccountBusiness.GetPagelist(offsetRows / rowsPerPage + 1, rowsPerPage, exp, "CreateDate desc", false).ToList();
                int count = agentSamaccountBusiness.GetListCount(exp, false);
                return Json(new { total = count, rows = list });
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "获取代理商分页列表信息失败", $"rowsPerPage={rowsPerPage}，offsetRows={offsetRows}，agentSamAccount={JsonConvert.SerializeObject(agentSamAccount)}", ex, "DapperCore");
                return Json(new { total = 0, rows = new List<AgentSamAccount>() });
            }
        }

        public IActionResult Add(string nodeJson, string creator, string createDate)
        {
            if (string.IsNullOrEmpty(creator))
            {
                return Json(new { success = false, message = "登录信息已过期，请刷新后重试！" });
            }

            #region 完善AgentSamAccount
            List<AgentSamAccount> agentSamAccounts = JsonConvert.DeserializeObject<List<AgentSamAccount>>(nodeJson);
            for (int i = 0; i < agentSamAccounts.Count; i++)
            {
                agentSamAccounts[i].Id = Guid.NewGuid().ToString();
                agentSamAccounts[i].AgentCode = agentSamAccounts[i].AgentCode.PadLeft(5, '0');
                agentSamAccounts[i].SamAccount = "OP" + agentSamAccounts[i].AgentCode.PadLeft(5, '0');
                agentSamAccounts[i].State = "submitted";
                agentSamAccounts[i].Creator = creator;
                agentSamAccounts[i].CreateDate = DateTime.Now;
            }
            #endregion

            new AgentSamAccountBusiness().AddList(agentSamAccounts);
            return Json(new { success = true, message = "添加成功！" });
        }

        [HttpPost]
        public ActionResult UpdateSamAccount(AgentSamAccount samaccount)
        {
            try
            {
                samaccount.Modifier = SessionUtility.GetBasicUserInfo().PinyinCode;
                samaccount.ModifyDate = DateTime.Now;
                bool success = new AgentSamAccountBusiness().UpdateNotNull(samaccount);
                return Json(new { Success = success, Message = success ? "修改成功" : "修改失败" });
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "更新代理商信息失败", $"samaccount={JsonConvert.SerializeObject(samaccount)}", ex, "DapperCore");
                return Json(new { Success = false, Message = "修改失败" });
            }
        }

        public IActionResult IsExist(string agentCode, string agentId = "")
        {
            try
            {
                bool exist = new AgentSamAccountBusiness().IsExist(agentCode, agentId);
                return Json(new { Exist = exist });
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "检查代理商编码是否存在失败", $"agentCode={agentCode}，agentId={agentId}", ex, "DapperCore");
                return Json(new { Exist = true });
            }

        }

        #region 导出到csv文件
        public FileResult ExportToCsv(AgentSamAccount agentSamAccount)
        {
            if (agentSamAccount.CreateDateEnd != null)
            {
                //申请截止日期是2019-02-02，查询数据应该包含02-02这一天，
                //由于前台只返回年月日，我们将截止日期改为02-03，然后申请日期<=02-03就能包含02-02的数据了
                agentSamAccount.CreateDateEnd = Convert.ToDateTime(agentSamAccount.CreateDateEnd).AddDays(1);
            }
            List<AgentSamAccount> agentList = new AgentSamAccountBusiness().GetList(GetExpression(agentSamAccount)).ToList();
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet sheet = package.Workbook.Worksheets.Add("代理商域账号信息");
                sheet.Cells[1, 1].Value = "代表处";
                sheet.Cells[1, 2].Value = "办事处";
                sheet.Cells[1, 3].Value = "地市";
                sheet.Cells[1, 4].Value = "代理商名称";
                sheet.Cells[1, 5].Value = "代理商编码";
                sheet.Cells[1, 6].Value = "域账号";
                sheet.Cells[1, 7].Value = "初始密码";
                sheet.Cells[1, 8].Value = "状态 ";
                sheet.Cells[1, 9].Value = "申请时间";

                for (int i = 0; i < agentList.Count; i++)
                {
                    sheet.Cells["A" + (i + 2)].Value = agentList[i].RepresentativeOffice;
                    sheet.Cells["B" + (i + 2)].Value = agentList[i].Office;
                    sheet.Cells["C" + (i + 2)].Value = agentList[i].City;
                    sheet.Cells["D" + (i + 2)].Value = agentList[i].AgentName;
                    sheet.Cells["E" + (i + 2)].Value = agentList[i].AgentCode;
                    sheet.Cells["F" + (i + 2)].Value = agentList[i].SamAccount;
                    sheet.Cells["G" + (i + 2)].Value = agentList[i].Password;
                    sheet.Cells["H" + (i + 2)].Value = agentList[i].State;
                    if (agentList[i].CreateDate != null)
                    {
                        sheet.Cells["I" + (i + 2)].Value = ((DateTime)agentList[i].CreateDate).ToString("yyyy-MM-dd HH:mm:ss");
                    }
                }

                sheet.Cells.AutoFitColumns(0);

                System.IO.MemoryStream output = new System.IO.MemoryStream();
                package.SaveAs(output);
                output.Position = 0;

                return File(output, "application/vnd.ms-excel", string.Format("代理商域账号信息{0}.xls", DateTime.Now.ToString("yyyyMMddHHmm")));
            }
        }
        #endregion

        [HttpPost]
        public ActionResult ImportData(string type)
        {
            try
            {
                string webRootPath = _hostingEnvironment.WebRootPath;
                IFormFile file = Request.Form.Files.GetFile("AccountFile");
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + file.FileName;
                fileName = Path.Combine("Upload\\AgentSamaccount", fileName);
                //文件保存的物理路径 
                string savePath = Path.Combine(_hostingEnvironment.WebRootPath, fileName);
                using (FileStream fs = new FileStream(savePath, FileMode.CreateNew))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                DataTable table = ExcelUtility.ReadExcelToDataTable(savePath);
                AgentSamAccountBusiness service = new AgentSamAccountBusiness();
                bool success = service.ImportData(table, type);
                if (success)
                {
                    return Json(new { Success = true, Message = "导入成功！" });
                }
                return Json(new { Success = false, Message = "导入失败，请联系管理员！" });
            }
            catch (Exception ex)
            {
                NlogUtility.WriteError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName, "导入代理商信息失败", "", ex, "DapperCore");
                return Json(new { Success = false, Message = "导入失败，请联系管理员！" });
            }
        }

        private Expression<Func<AgentSamAccount, bool>> GetExpression(AgentSamAccount agentSamaccount)
        {
            Expression<Func<AgentSamAccount, bool>> exp = a => a.CreateDate >= agentSamaccount.CreateDate && a.CreateDate <= agentSamaccount.CreateDateEnd
                                                                   && a.RepresentativeOffice.Contains(agentSamaccount.RepresentativeOffice) && a.Office.Contains(agentSamaccount.Office)
                                                                   && a.City.Contains(agentSamaccount.City) && a.AgentName.Contains(agentSamaccount.AgentName)
                                                                   && a.AgentCode == agentSamaccount.AgentCode;
            return exp;
        }
    }
}